package com.roubsite.cloud.controller;

import com.roubsite.cloud.bean.VerifyCode;
import com.roubsite.cloud.common.bean.Result;
import com.roubsite.cloud.common.service.RedisService;
import com.roubsite.cloud.common.utils.CreateImageCode;
import com.roubsite.cloud.common.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

@RestController
public class CaptchaController {
	@Autowired
	RedisService redisService;

	@GetMapping("captcha")
	public Result index(ServerHttpResponse response) throws IOException {
		int w = 200, h = 80;// 图片大小


		String code = CreateImageCode.generateVerifyCode(4);
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		CreateImageCode.outputImage(w, h, outputStream, code);
		String id = UuidUtils.getUuid();

		redisService.putRedis("captcha" + id, code, 300);
		VerifyCode verifyCode = new VerifyCode();
		verifyCode.setCaptchaBase64("data:image/png;base64,"+Base64.getEncoder().encodeToString(outputStream.toByteArray()));
		verifyCode.setCaptchaKey(id);
		return Result.setData(verifyCode);
	}


}
